<template>
    <div>
        <el-tabs v-model="activeName">
            <el-tab-pane label="入党申请" name="first">
                <div class="apply">
                    <!--step进度条-->
                    <div class="step">
                        <el-steps :active="active" finish-status="success" align-center>
                            <el-step title="入党申请"></el-step>
                            <el-step title="积极分子申请"></el-step>
                            <el-step title="发展对象申请"></el-step>
                            <el-step title="预备党员申请"></el-step>
                            <el-step title="正式党员转正"></el-step>
                        </el-steps>
                    </div>
                    <el-divider class="divider"></el-divider>
                    <div class="form">
                        <el-form ref="form" :rules="rules" :model="form" label-width="80px">

                            <el-form-item label="学号" prop="studentId" sortable>
                                <el-col :span="20">
                                    <el-input v-model="form.studentId" disabled></el-input>
                                </el-col>
                            </el-form-item>

                            <el-form-item label="姓名" prop="name">
                                <el-col :span="20">
                                    <el-input v-model="form.name" disabled></el-input>
                                </el-col>
                            </el-form-item>

                            <el-form-item label="身份" prop="userIdentity">
                                <el-col :span="20">
                                    <el-input v-model="userIdentityText" disabled>
                                    </el-input>
                                </el-col>
                            </el-form-item>

                            <el-form-item label="组织" prop="organization">
                                <el-col :span="20">
                                    <el-select v-model="form.organization" disabled style="margin-left: 5px;">
                                        <el-option
                                                v-for="item in organizationsData"
                                                :key="item.code"
                                                :label="item.name"
                                                :value="item.code">
                                        </el-option>
                                    </el-select>
                                </el-col>
                            </el-form-item>

                            <el-form-item label="申请文件" prop="file">
                                <el-col :span="20">
                                    <el-upload
                                            class="upload-demo"
                                            :action="'http://'+ serverIp +':8090/sys-file/upload'"
                                            :on-success="handleSuccess"
                                            :before-upload="handleBeforeUpload"
                                            multiple
                                            :limit="1"
                                            :file-list="fileList"
                                            :disabled="identityDis">
                                        <el-button size="small" type="primary" :disabled="identityDis">点击上传</el-button>
                                        <div slot="tip" class="el-upload__tip">
                                            文件最大10M
                                        </div>
                                    </el-upload>
                                </el-col>
                            </el-form-item>
                        </el-form>
                        <el-button type="success" style="margin-left:300px;" :disabled="identityDis" @click="open">申请
                        </el-button>
                    </div>


                </div>
            </el-tab-pane>

            <el-tab-pane label="申请历史" name="second">
                <!------用户管理查询按钮------>
                <div class="search">

                    <el-select v-model="userIdentity" filterable placeholder="请选择身份">
                        <el-option
                                v-for="item in userIdentitys"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                        </el-option>
                    </el-select>

                    <el-button type="primary" style="margin-left: 10px;" @click="loadPost">查询</el-button>
                    <el-button type="warning" @click="resetParam">重置</el-button>
                </div>


                <!------信息展示列表------>
                <el-table :data="tableData"
                          :header-cell-style="{color:'#c71111'}">
                    <el-table-column prop="id" label="ID" width="50">
                    </el-table-column>

                    <el-table-column prop="studentId" label="学号" width="160">
                    </el-table-column>

                    <el-table-column prop="name" label="姓名" width="120">
                    </el-table-column>

                    <el-table-column prop="userIdentity" label="身份" width="120">
                        <template slot-scope="scope">
                            <el-tag
                                    :type="scope.row.userIdentity === 6 ? 'danger' : scope.row.userIdentity === 5 ? 'warning' :scope.row.userIdentity === 4 ? 'success' : scope.row.userIdentity === 3 ? 'primary' : 'info'"
                                    disable-transitions>{{scope.row.userIdentity === 6?'中共党员'
                                :(scope.row.userIdentity===5?'中共预备党员'
                                :(scope.row.userIdentity===4?'发展对象'
                                :(scope.row.userIdentity===3?'积极分子'
                                :'入党成员')))}}
                            </el-tag>
                        </template>
                    </el-table-column>

                    <el-table-column prop="approver" label="审批人" width="120">
                    </el-table-column>

                    <el-table-column prop="organization" label="组织" width="200" :formatter="formatOrganizations">
                    </el-table-column>

                    <el-table-column prop="createtime" label="申请时间" width="200">
                    </el-table-column>

                    <el-table-column prop="download" label="文件" width="180">
                        <template slot-scope="scope">
                            <el-button type="primary" v-if="scope.row.fileUrl" size="small"
                                       @click="window.open(scope.row.fileUrl)" :disabled="scope.row.downFile">
                                下载申请文件
                            </el-button>
                        </template>
                    </el-table-column>

                    <el-table-column prop="statu" label="状态">
                        <template slot-scope="scope">
                            <el-tag
                                    :type="scope.row.statu == 1 ? 'primary' : scope.row.statu == 2 ? 'success' : 'danger'"
                                    disable-transitions>{{scope.row.statu == 1 ? '待审批' : scope.row.statu == 2 ? '已通过' :
                                '未通过'}}
                            </el-tag>
                        </template>
                    </el-table-column>
                </el-table>
                <!------分页查询------>
                <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="pageNum"
                        :page-sizes="[5, 8, 18, 30]"
                        :page-size="pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total">
                </el-pagination>
            </el-tab-pane>
        </el-tabs>
    </div>
</template>

<script>
    import {serverIp} from "../../../public/config";

    export default {
        name: "ApplyManage",
        data() {
            return {
                serverIp: serverIp,
                window: window,
                fileList: [],
                activeName: 'first',
                active: 0,
                users: JSON.parse(sessionStorage.getItem('CurUser')),
                organizationsData: [],
                tableData: [],
                pageSize: 8,
                pageNum: 1,
                total: 0,
                currentRow: {},
                name: '',
                userIdentity: '',
                userIdentitys: [
                    {
                        value: '5',
                        label: '中共预备党员'
                    }, {
                        value: '4',
                        label: '发展对象'
                    }, {
                        value: '3',
                        label: '积极分子'
                    }, {
                        value: '2',
                        label: '群众'
                    }
                ],

                centerDialogVisible: false,
                form: {
                    id: '',
                    studentId: '',
                    name: '',
                    userIdentity: '',
                    approver: '',
                    organization: '',
                    statu: '1',
                    fileUrl: '',
                },
                rules: {}

            };
        },
        computed: {
            userIdentityText() {
                switch (this.form.userIdentity) {
                    case 6:
                        return '中共党员';
                    case 5:
                        return '中共预备党员';
                    case 4:
                        return '发展对象';
                    case 3:
                        return '积极分子';
                    default:
                        return '入党成员';
                }
            },
            identityDis() {
                const users = JSON.parse(sessionStorage.getItem('CurUser'));
                return users.userIdentity === 6
            },
        },
        methods: {
            // download(url) {
            //     // 创建一个虚拟链接，通过转跳实现文件下载
            //     const link = document.createElement('a');
            //     link.href = url;
            //     link.download = '申请文件'; // 设置文件名
            //     document.body.appendChild(link);
            //     link.click();
            //     document.body.removeChild(link);
            // },
            handleSuccess(res) {
                if (res) {
                    console.log(res)
                    this.form.fileUrl = res;
                    this.$message.success("上传成功")
                } else {
                    this.$message.error("上传失败");
                }
            },
            handleBeforeUpload(file) {
                const isLt10M = file.size / 1024 / 1024 < 10;

                if (!isLt10M) {
                    this.$message.error('上传文件大小不能超过 10MB!');
                }
                return isLt10M;
            },

            stepById() {
                this.active = this.users.userIdentity - 1;
            },

            pass() {
                this.form.statu = 2;
                this.form.approver = this.users.name;
                this.$axios.post('http://'+ serverIp +':8090/apply/update', this.form)
                    .then(res => res.data).then(res => {
                    console.log(res);
                    if (res.code == 200) {
                        this.$message({
                            message: '操作成功！',
                            type: 'success'
                        });
                        this.centerDialogVisible = false;
                        this.loadPost();
                        this.resetForm()
                    } else {
                        this.$message({
                            message: '操作失败！',
                            type: 'error'
                        });
                    }
                })
            },
            refuse() {
                this.form.statu = 3;
                this.form.approver = this.users.name;
                this.$axios.post('http://'+ serverIp +':8090/apply/update', this.form)
                    .then(res => res.data).then(res => {
                    console.log(res);
                    if (res.code == 200) {
                        this.$message({
                            message: '操作成功！',
                            type: 'success'
                        });
                        this.centerDialogVisible = false;
                        this.loadPost();
                        this.resetForm()
                    } else {
                        this.$message({
                            message: '操作失败！',
                            type: 'error'
                        });
                    }
                })

            },
            userIdentityLabel() {
                let item = this.userIdentitys.find((u) => u.value === this.form.userIdentity);
                return item ? item.label : '';
            },


            formatOrganizations(row) {
                let temp = this.organizationsData.find(item => {
                    return item.code == row.organization
                });

                return temp && temp.name
            },

            mounted() {
                // 获取当前用户信息
                const users = JSON.parse(sessionStorage.getItem('CurUser'))
                // 将当前用户的机构名赋值给 form 对象的 organization 属性
                this.form.organization = this.users.organization;
                this.form.studentId = this.users.studentId;
                this.form.name = this.users.name;
                this.form.userIdentity = this.users.userIdentity;
            },

            resetForm() {
                this.$refs.form.resetFields();
            },

            open() {
                this.$confirm('是否提交申请?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.save();
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消提交！'
                    });
                });
            },

            save() {
                this.$axios.post('http://'+ serverIp +':8090/apply/duplicate', this.form)
                    .then(response => {
                        if (response.data.code === 200) {
                            this.doSave(); // 执行保存操作
                        } else {
                            this.$message.error('请勿重复申请'); // 弹出错误信息
                        }
                    })
                    .catch(error => {
                        this.$message.error('保存失败！');
                    });
            },
            doSave() {
                this.$axios.post('http://'+ serverIp +':8090/apply/save', this.form)
                    .then(res => res.data).then(res => {
                    console.log(res);
                    if (res.code == 200) {
                        this.$message({
                            message: '操作成功！',
                            type: 'success',
                        });
                        this.centerDialogVisible = false;
                        this.fileList = [];
                        this.loadPost();
                        this.resetForm()
                    } else {
                        this.$message({
                            message: '操作失败！',
                            type: 'error'
                        });
                    }
                })
            },

            add() {
                this.centerDialogVisible = true;
                this.$nextTick(() => {
                    this.resetForm();
                })
            },

            resetParam() {
                this.userIdentity = '';
                this.loadPost()
            },

            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
                this.pageNum = 1;
                this.pageSize = val;
                this.loadPost()
            },
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
                this.pageNum = val;
                this.loadPost()
            },

            loadGet() {
                this.$axios.get('http://'+ serverIp +':8090/apply/list').then(res => res.data).then(res => {
                    console.log(res)
                })
            },

            loadPost() {
                const users = JSON.parse(sessionStorage.getItem('CurUser'));
                this.$axios.post('http://'+ serverIp +':8090/apply/myPage', {
                    pageSize: this.pageSize,
                    pageNum: this.pageNum,

                    param: {
                        studentId: this.users.studentId,
                        userIdentity: this.userIdentity,
                    }
                }).then(res => res.data).then(res => {
                    console.log(res);
                    if (res.code == 200) {
                        this.tableData = res.data
                        this.total = res.total
                    } else {
                        alert('获取数据失败')
                    }

                })
            },

            loadOrganizations() {
                this.$axios.get('http://'+ serverIp +':8090/organizations/list').then(res => res.data).then(res => {
                    console.log(res)
                    if (res.code == 200) {
                        this.organizationsData = res.data
                    } else {
                        alert('获取数据失败')
                    }
                })
            },
        },

        beforeMount() {
            // this.loadGet();
            this.loadPost();
            this.loadOrganizations();
            this.stepById();
            this.mounted();
        },
    }
</script>

<style scoped>
    .divider {
        margin-bottom: 40px;
    }

    .form {
        max-width: 700px;
        margin: 0 auto;
    }

    .step {
        margin-top: 40px;
        margin-bottom: 40px;
    }

    .search {
        margin-bottom: 5px;
    }
</style>